package com.relivethefuture.bidule.model
{
	import mx.collections.ArrayCollection;
	import flash.filesystem.File;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	import flash.events.Event;
	import mx.events.FileEvent;

	public class Catalog
	{
		private var entries:ArrayCollection;
		private var docsDir:File;
		
		private static var biduleVersion:String = "0.95";
		
		public function Catalog()
		{
			entries = new ArrayCollection();
			docsDir = File.documentsDirectory;
			docsDir.addEventListener(Event.SELECT,saveData);
		}
		
		public function addEntry(entry:CatalogEntry):void
		{
			entries.addItem(entry);
		}

		public function clear():void
		{
			entries.removeAll();
		}
		
		public function getEntries():ArrayCollection
		{
			return entries;
		}
		
		public function save(groups:ArrayCollection):void
		{
			entries.removeAll();
			for(var n:Number = 0;n<groups.length;n++)
			{
				var g:Group = Group(groups.getItemAt(n));
				var e:CatalogEntry = new CatalogEntry(g);
				addEntry(e);
			}

			try
			{
    			docsDir.browseForSave("Save As");
			}
			catch (error:Error)
			{
				trace("Failed:", error.message);
				return;
			}
		}
		
		private function saveData(event:Event):void
		{
			var f:File = event.target as File;
			
			var xml:String = '<?xml version="1.0" encoding="iso-8859-1"?>\n';
			xml += '<!DOCTYPE Catalog SYSTEM "Catalog.dtd">\n';
			xml += "<Catalog>\n"

			for(var i:Number = 0;i<entries.length;i++)
			{
				var entry:CatalogEntry = CatalogEntry(entries.getItemAt(i));
				xml += '<CatalogEntry name="' + entry.name + '" type="' + entry.type + '"';
				xml += ' url="' + entry.url + '" version="' + entry.version + '" author="' + entry.author + '"';
				xml += ' email="' + entry.email + '" biduleVersion="' + biduleVersion + '">' + entry.description + '</CatalogEntry>\n';
			}
			
			xml += "</Catalog>\n";
			
			var stream:FileStream = new FileStream();
			stream.open(f, FileMode.WRITE);
			stream.writeUTFBytes(xml);
			stream.close();			
		}
	}
}